import { TRPCError, initTRPC } from '@trpc/server';
import { createContextInner } from './context';


export type Context = Awaited<ReturnType<typeof createContextInner>>;

const t = initTRPC.context<typeof createContextInner>().create();

export const publicProcedure = t.procedure;

export const router = t.router;

export const mergeRouters = t.mergeRouters;

// 鉴权的程序
export const authProcedure = publicProcedure.use(async (opts) => {
    const { ctx } = opts;
    if (!ctx.session?.user) {
        throw new TRPCError({ code: 'UNAUTHORIZED' });
    }
    return opts.next({ ctx });
});

// 创建服务端调用在示例仓库中使用的是 createCaller, 但是 createCaller 在 trpc v11 中已经废弃
// @see https://trpc.io/docs/server/server-side-calls#create-caller
export const createCallerFactory = t.createCallerFactory;
